#include "pdftool.h"

PDFTool::PDFTool(QString fileName)
{
	document = Poppler::Document::load(fileName);
	if (!document || document->isLocked()) {
		delete document;
		document = NULL;
	}
}

PDFTool::~PDFTool()
{
	delete document;
}

bool PDFTool::isLoaded()
{
	return document != NULL;
}

QString PDFTool::guessTitle()
{
	if (!isLoaded())
		return QString();

	if (document->numPages() <= 0)
		return QString();

	Poppler::Page* pdfPage = document->page(0);
	if (!pdfPage) {
		return QString();
	}

	QList<Poppler::TextBox*> textBoxes = pdfPage->textList();

	qreal maxY = 1.0e99;
	foreach (Poppler::TextBox* box, textBoxes) {
		QString text = box->text().toLower();
		if (text.contains("abstract")) {
			maxY = qMin(maxY, box->boundingBox().top());
		}
	}

	int maxHeight = 0;
	foreach (Poppler::TextBox* box, textBoxes) {
		if (box->boundingBox().top() >= maxY)
			continue;
		maxHeight = qMax(maxHeight, qRound(box->boundingBox().height()));
	}

	QString title;
	foreach (Poppler::TextBox* box, textBoxes) {
		if (qRound(box->boundingBox().height()) == maxHeight) {
			title += box->text() + " ";
		}
	}

	foreach (Poppler::TextBox* box, textBoxes) {
		delete box;
	}

	delete pdfPage;

	title = title.trimmed();
	if (!title.isEmpty()) {
		title = title.mid(0, 1).toUpper() + title.mid(1).toLower();
	}
	return title;
}

int PDFTool::pageCount()
{
	if (!isLoaded())
		return 0;

	if (document->numPages() < 0)
		return 0;

	return document->numPages();
}

QString PDFTool::fullText()
{
	if (!isLoaded())
		return QString();

	if (document->numPages() <= 0)
		return QString();

	QString result;

	for (int iPage = 0; iPage < document->numPages(); iPage++) {
		Poppler::Page* pdfPage = document->page(iPage);
		if (!pdfPage) {
			continue;
		}

		QList<Poppler::TextBox*> textBoxes = pdfPage->textList();

		foreach (Poppler::TextBox* box, textBoxes) {
			QString text = box->text().trimmed();
			result += (result.isEmpty() ? QString("") : QString(" ")) + text;
		}

		foreach (Poppler::TextBox* box, textBoxes) {
			delete box;
		}

		delete pdfPage;
	}

	return result;
}
